package com.fable.sp.core.service.impl;

import com.fable.sp.core.template.TemplateNotFoundException;
import com.fable.sp.core.template.TemplateRenderer;
import com.fable.sp.core.template.freemarker.WidgetHttpScopesHashModel;
import com.fable.sp.core.widget.WidgetException;
import com.fable.sp.core.widget.WidgetRenderer;
import com.fable.sp.core.widget.WidgetRequest;
import com.fable.sp.core.widget.WidgetResponse;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import java.util.Map;

/**
 * .
 *
 * @author stormning on 16/8/9.
 */
@Service
public class WidgetRendererImpl implements WidgetRenderer {

    @Autowired
    private TemplateRenderer templateRenderer;

    @Override
    public String render(WidgetRequest widgetRequest, WidgetResponse response) throws WidgetException {
        Map<String, Object> params = Maps.newHashMap();
        params.put(WidgetHttpScopesHashModel.WIDGET_REQUEST_KEY, widgetRequest);
        try {
            return templateRenderer.renderNamedTemplate(getTemplateName(widgetRequest), params);
        } catch (TemplateNotFoundException ex) {
            if ("preference".equals(widgetRequest.getWidgetMode().toString())) {
                return templateRenderer.renderNamedTemplate("/global/" + WidgetRenderer.PREFER_TEMPLATE + ".ftl", params);
            }
            throw ex;
        }
    }

    protected String getTemplateName(WidgetRequest widgetRequest) {
        return "/widgets/" + ClassUtils.getShortName(widgetRequest.getWidgetInstance().getWidgetName()) + "_" + widgetRequest.getWidgetMode().toString() + ".ftl";
    }
}
